package top.whysu.rongcloud.global;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import top.whysu.rongcloud.constant.CodeConstant;
import top.whysu.rongcloud.dto.http.Response;
import top.whysu.rongcloud.exception.BusinessException;
import top.whysu.rongcloud.util.ResponseUtil;

import javax.servlet.http.HttpServletResponse;

/**
 * @version:
 * @description: 视图层全局异常捕获
 * @copyright:
 * @company:
 * @author:
 * @date:
 */
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务异常
     *
     * @param response          响应信息
     * @param businessException 业务异常
     * @return 自定义响应
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Response processBusinessException(HttpServletResponse response, BusinessException businessException) {
        // 日志打印
        LOGGER.error(businessException.getMessage(), businessException);
        // 封装HTTP响应
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        // 封装自定义响应
        return ResponseUtil.getResponse(businessException.getCode(), businessException.getMessage(), null);
    }

    /**
     * Validated校验参数错误异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected Response validationBodyException(HttpServletResponse response, MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        // 封装HTTP响应
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        String message;
        if (StringUtils.isNotEmpty(fieldError.getDefaultMessage())) {
            message = fieldError.getDefaultMessage();
        } else {
            message = String.format("%s参数错误", fieldError.getField());
        }
        return ResponseUtil.getResponse(CodeConstant.Http.PARAM_ERROR, message, null);
    }

}
